<template>
  <div class>
    <!-- 路由渲染 -->
    <router-view></router-view>
    <!-- 底部选项卡 -->
    <van-tabbar fixed v-model="active" @change="tabChange">
      <van-tabbar-item
        replace
        v-for="(item, index) in tabbarList"
        :key="index"
        :icon="item.icon"
        :to="item.path"
        >{{ item.title }}</van-tabbar-item
      >
    </van-tabbar>
  </div>
</template>


<script>
import { setInterval } from "timers";
import $ from "jquery";
export default {
  data() {
    return {
      active: 0, //底部选项卡
      tabbarList: [
        {
          path: "/home",
          title: "首页",
          icon: "home-o",
        },
        {
          path: "/qrs",
          title: "分类",
          icon: "qr",
        },
        {
          path: "/chat",
          title: "消息",
          icon: "chat-o",
        },
        {
          path: "/cart",
          title: "购物车",
          icon: "cart-o",
        },
        {
          path: "/user",
          title: "我的",
          icon: "user-o",
        },
      ],
    };
  },
  methods: {
    tabChange(index) {
      //更新tabbar改变时的active-索引
      //保存active，防止页面刷新后丢失
      sessionStorage.setItem("tabsActive", this.active);
      //重写高亮事件，tabbar一切换就发生高亮
      $(".van-tabbar-item")
        .removeClass("van-tabbar-item--active")
        .eq(index)
        .addClass("van-tabbar-item--active");
    },
    activeTab(path) {//通过监听路由同步底部选项卡高亮
      var index = this.tabbarList.map((item) => item.path).indexOf(path);
      if (index != -1) {
        this.active = index;
      }
    },
  },
  created() {},
  mounted() {
    //页面刷新时重新获取this.active的值
    this.active = sessionStorage.getItem("tabsActive");
    //解决刷新后tabbar不高亮的问题
    $(".van-tabbar-item")
      .removeClass("van-tabbar-item--active")
      .eq(this.active)
      .addClass("van-tabbar-item--active");
  },
  watch: {
    $route(to) {
      this.activeTab(to.path);
    },
  },
};
</script>

<style scoped>
* {
  touch-action: none;
}
</style>